package com.fdb.efp.nls.service.impl.loan_repay;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fdb.basic.framework.core.exception.ESBException;
import com.fdb.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.fdb.efp.basic.framework.mq.constant.TagEnums;
import com.fdb.efp.basic.framework.mq.constant.TopicEnums;
import com.fdb.efp.esb.service.bo.req.sed.repay.ReqLoanRepayResultQryBean;
import com.fdb.efp.esb.service.bo.resp.sed.repay.RespLoanRepayResultQryBean;
import com.fdb.efp.esb.service.facade.sed.repay.LoanRepayResultQryService;
import com.fdb.efp.nls.service.facade.LoanRepayDetailService;
import com.fdb.efp.loan.service.vo.LoanRepayDetailVO;
import com.fdb.efp.nls.common.constant.NlsApplyInfoEnums;
import com.fdb.efp.nls.common.constant.psd.NlsReplyFlowStatus;
import com.fdb.efp.nls.common.constant.sed.DealState;
import com.fdb.efp.nls.common.constant.sed.SedNlsEnum;
import com.fdb.efp.nls.service.impl.LoanReleaseOrRepayQueueHangHandle;
import com.fdb.efp.nls.service.impl.psd.repay.PsdRepaymentInfoSyncServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

import static com.fdb.basic.framework.core.constant.BaseConstant.RY_STS_0;
import static com.fdb.efp.nls.common.constant.psd.NlsReplyFlowStatus.FLOW_STATUS_5;

/**
 * 需求编号:2019D08--
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/11/6
 * 功能描述:
 * 修改日期:2019/11/6
 * 修改描述:
 */
@Service("repayCompensationTask")
public class RepayCompensationTask extends CompensationTask<LoanRepayDetailVO> {

    private static Logger logger = LoggerFactory.getLogger(RepayCompensationTask.class);

    @Override
    protected void updateStatus(LoanRepayDetailVO loanRepayDetailVO) throws ESBException {
        if (loanRepayDetailVO.getExecuteTime() + 1 == 218) {
            LoanRepayDetailVO updateNlsApplyInfo =
                    updateRepayDetailFailureStatus(loanRepayDetailVO);

            loanRepayDetailService.updateByPk(updateNlsApplyInfo);
            return;
        }

        String globalSerno = loanRepayDetailVO.getGlobalSerno();
        // 根据提前还款申请传送过来的全局流水号，调用贷款回收结果查询
        ReqLoanRepayResultQryBean reqLoanRepResQryBean = new ReqLoanRepayResultQryBean();
        reqLoanRepResQryBean.setTxnGlblSrlNo(globalSerno);
        RespLoanRepayResultQryBean respLoanRepResQryBean = new RespLoanRepayResultQryBean();
        respLoanRepResQryBean = loanRepayResultQryService.loanRepayResultQry(reqLoanRepResQryBean);

        String isRepay = respLoanRepResQryBean.getQrySt();

        //交易状态
        String dealState = respLoanRepResQryBean.getTxnStCd();
        LoanRepayDetailVO updateLoanRepayDetail = null;

        if (DealState.SUCCESS.getValue().equals(dealState)) {
            //通过借据号获取借据信息
            try {
                // 进行同步处理
                psdRepaymentInfoSyncService.doExecute(null, updateLoanRepayDetail);
            } catch (Exception e) {
                updateLoanRepayDetail = updateRepayDetailHandling(loanRepayDetailVO);
                logger.info("用信申请流水号【" + loanRepayDetailVO.getSetlSeq() + "】还款成功,执行同步失败 等待同步任务处理");
            }
        } else if (DealState.FAIL.getValue().equals(dealState) ||
                SedNlsEnum.QuerySts.WITHOUT.getValue().equals(isRepay) && StringUtils.isEmpty(dealState)) {
            // 更新对应的还款明细表状态
            updateLoanRepayDetail = updateRepayDetailFailureStatus(loanRepayDetailVO);
        } else if (DealState.DEALING.getValue().equals(dealState) ||
                DealState.UNKNOW.getValue().equals(dealState) ||
                DealState.SUSPEND.getValue().equals(dealState)) {
            logger.info("还款申请流水号【" + loanRepayDetailVO.getSetlSeq() + "】 放款补偿任务正在执行 当前执行的次数为【" + loanRepayDetailVO.getExecuteTime() + "】");
            logger.info("还款申请流水号【" + loanRepayDetailVO.getSetlSeq() + "】 还款申请为" + JSONObject.toJSONString(loanRepayDetailVO));
            throw new ESBException("还款款补偿任务执行");
        }
        loanRepayDetailService.updateByPk(updateLoanRepayDetail);
    }

    private LoanRepayDetailVO updateRepayDetailFailureStatus(LoanRepayDetailVO loanRepayDetailVO) {
        //设置审批状态信息为失败
        loanRepayDetailVO.setWfApprSts(NlsApplyInfoEnums.NlsApplyState.REJECT.getKey());
        loanRepayDetailVO.setRpSts(RY_STS_0);
        loanRepayDetailVO.setFlowStatus(NlsReplyFlowStatus.FLOW_STATUS_4);
        return loanRepayDetailVO;
    }

    private LoanRepayDetailVO updateRepayDetailHandling(LoanRepayDetailVO loanRepayDetailVO) {
        loanRepayDetailVO.setWfApprSts(NlsApplyInfoEnums.NlsApplyState.DEALING.getKey());
        loanRepayDetailVO.setRpSts("1");
        loanRepayDetailVO.setFlowStatus(FLOW_STATUS_5);
        return loanRepayDetailVO;
    }

    @Override
    protected void sendMessage(LoanRepayDetailVO loanRepayDetailVO) {
        try {

            int executeTime = loanRepayDetailVO.getExecuteTime();

            loanRepayDetailVO.setExecuteTime(++executeTime);
            loanRepayDetailService.updateByPk(loanRepayDetailVO);

            logger.info("还款申请流水号【" + loanRepayDetailVO.getSetlSeq() + "】 放款补偿任务正在执行 当前执行的次数为【" + loanRepayDetailVO.getExecuteTime() + "】 延迟执行级别【" + delayLevel(loanRepayDetailVO.getExecuteTime()) + "】");
            Message message = new Message(TopicEnums.LOANRELEASEORREPAY_QUEUE_TASK_TOPIC.getTopicId(), TagEnums.LOANRELEASEORREPAY_QUEUE_TASK.getTagId(),
                    loanRepayDetailVO.getSetlSeq().concat(".").concat(LoanReleaseOrRepayQueueHangHandle.LOANREPAYDETAILVO + loanRepayDetailVO.getExecuteTime()),
                    JSON.toJSONString(loanRepayDetailVO).getBytes("UTF-8"));
            message.setDelayTimeLevel(delayTimes(loanRepayDetailVO.getExecuteTime()));
            producerService.sendMsg(message);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("还款申请流水号【" + loanRepayDetailVO.getSetlSeq() + "】执行放款补偿任务时，发送mq出现异常!!!");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("还款申请流水号【" + loanRepayDetailVO.getSetlSeq() + "】执行放款补偿任务时，更新补偿任务执行次数失败!!!");
        }
    }

    @Override
    protected LoanRepayDetailVO convertToJavaBean(String body) {
        return JSONObject.parseObject(body, LoanRepayDetailVO.class);
    }

    @Autowired
    @Qualifier("loanRepayResultQryService")
    private LoanRepayResultQryService loanRepayResultQryService;

    @Autowired
    @Qualifier("loanRepayDetailService")
    private LoanRepayDetailService loanRepayDetailService;

    /**
     * mq
     */
    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;


    @Autowired
    @Qualifier("repaymentInfoSyncService")
    private PsdRepaymentInfoSyncServiceImpl psdRepaymentInfoSyncService;
    /*@Qualifier("yedRepaymentInfoSyncService")
    private YedRepaymentInfoSyncServiceImpl psdRepaymentInfoSyncService;*/

}
